package com.loyal.loyalerp.humenresource.employee.api;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.loyal.loyalerp.basedata.company.mapper.GyCompanyMapper;
import com.loyal.loyalerp.basedata.department.mapper.DepartmentMapper;
import com.loyal.loyalerp.basedata.department.model.Department;
import com.loyal.loyalerp.basedata.department.service.DepartmentService;
import com.loyal.loyalerp.basedata.person_predept.model.GyPersonPredept;
import com.loyal.loyalerp.basedata.person_predept.service.PredeptService;
import com.loyal.loyalerp.commons.ServerResponse;
import com.loyal.loyalerp.humenresource.categoryDetail.mapper.Gy_ConfigDetailMapper;
import com.loyal.loyalerp.humenresource.employee.entity.ErroMsg;
import com.loyal.loyalerp.humenresource.employee.entity.Gy_Person;
import com.loyal.loyalerp.humenresource.employee.mapper.Gy_PersonMapper;
import com.loyal.loyalerp.humenresource.employee.service.Gy_PersonReadService;
import com.loyal.loyalerp.humenresource.employee.service.Gy_PersonWriteService;
import com.loyal.loyalerp.mapper.GyPersonMapper;
import com.loyal.loyalerp.mapper.KaoQinMapper;
import com.loyal.loyalerp.model.GyPerson;
import com.loyal.loyalerp.model.KaoQinMessage;
import com.loyal.loyalerp.model.vo.PersonBaseData;
import com.loyal.loyalerp.service.EmployeeService;
import com.loyal.loyalerp.service.impl.KaoQinServiceImpl;
import com.loyal.loyalerp.utils.ExcelRead;
import com.loyal.loyalerp.utils.ExcelUtil;
import com.loyal.loyalerp.utils.WorkDayMath;

@Controller
@RequestMapping("/employee")
public class Gy_PersonApi {

	@Autowired
	private Gy_PersonReadService readService;

	@Autowired
	Gy_PersonMapper personMapper;

	@Autowired
	private Gy_PersonWriteService writeService;

	@Autowired
	private EmployeeService employService;

	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private DepartmentMapper departmentMapper;

	@Autowired
	private KaoQinServiceImpl kaoqinService;

	@Autowired
	private KaoQinMapper kaoqinMapper;

	@Autowired
	GyCompanyMapper companyMapper;

	@Autowired
	private PredeptService predeptService;

	@Autowired
	Gy_ConfigDetailMapper configDetailMapper;

	@Autowired
	GyPersonMapper employeeMapper;

	@RequestMapping("/jsp")
	public String catttt(Model model) {
		List<Department> departments = departmentService.selectByExample(null);
		model.addAttribute("departments", departments);
		return "HumenResource/Employee/employee";
	}

	@RequestMapping("/editjsp")
	public String editjsp() {
		return "HumenResource/Employee/editEmployee";
	}

	@ResponseBody
	@RequestMapping("/list")
	public List<Gy_Person> listPerson(String AddEditDel, String _search, String dname, String cname, String pname,
			String searchField, String searchString) {
		if ("false".equals(_search)) {
			return readService.listPerson();
		} else if ("true".equals(_search)) {
			if ("addEditDel".equals(AddEditDel)) {
				return readService.listPerson();
			}
			if ("active".equals(searchField) && ((pname == null && cname == null && dname == null)
					|| ("".equals(pname) && "".equals(cname) && "".equals(dname)))) {
				return readService.selectByActive(searchString);
			} else {
				return readService.selectByPCD(searchString, pname, cname, dname);
			}
		}
		return null;
	}

	@ResponseBody
	@RequestMapping("/deleteEmployee")
	public String deleteEmployee(Long id) {
		writeService.deleteById(id);
		return "success";
	}

	// 异常处理的错误
	@ExceptionHandler(value = { Exception.class })
	public @ResponseBody ErroMsg sendErro(Exception e) {
		ErroMsg msg = new ErroMsg();
		msg.setStatus(400);
		msg.setMsg("后台出错" + e.getMessage());
		return msg;
	}

	@ResponseBody
	@RequestMapping("/add")
	public Map<String, Object> EmployeeAdd(Gy_Person employee) throws ParseException {
		Map<String, Object> map = new HashMap<String, Object>();
		// 判断工号有没有重复
		int countCode = writeService.selectPersonCodeHasExist(employee.getPersoncode());
		if (countCode > 0) {
			map.put("status", 400);
			map.put("msg", "工号已经存在添加失败");
		} else {
			try {
				int id = writeService.insert(employee);
				map.put("status", 200);
				map.put("msg", "新增成功");
				map.put("msg", "success");
			} catch (Exception e) {
				e.printStackTrace();
				map.put("status", 400);
				map.put("msg", e.getMessage());
			}
			map.put("data", employee);

			// 在员工部门调动表插入一条记录
			int personid = employee.getId().intValue();
			int deptid = employee.getDeptid();
			Date nowdate = new Date();
			GyPersonPredept predept = new GyPersonPredept(personid, deptid, nowdate);
			predeptService.insertPredept(predept);

			// 判断当前年份有没有初始化
			int count = kaoqinService.selectYearHasInit((new Date().getYear() + 1900),
					employee.getCompanyid().intValue());
			if (count > 0) {
				Date date1 = new Date();
				String years = date1.getYear() + 1900 + "";
				// 计算每个月上班天数
				int workDayMonth[] = WorkDayMath.importDate(years);
				// 计算年度上班总数期初数
				int workDaysTotal = 0;
				for (int monthWorkDay : workDayMonth) {
					workDaysTotal = workDaysTotal + monthWorkDay;
				}

				PersonBaseData person = new PersonBaseData();
				person.setCompanyId(employee.getCompanyid().intValue());
				person.setCompanyName(employService.selectCompanyNameById(employee.getCompanyid().intValue()));
				person.setPersonId(employee.getId().intValue());
				person.setPersonName(employee.getPersonname());
				person.setOfficeDate(employee.getOfficedate());
				Date officeDate = employee.getOfficedate();
				// 判断当前用户有没有入职超过一年,如果没有超过一年，按照比例折算假期
				Date date = new Date();
				int officeYear = officeDate.getYear();
				// 当前的年份
				Date nowDate = new Date();
				// 定义放假天数
				float Holidays = 0;
				float HolidaysEnd = 0;
				int nowYear = nowDate.getYear();
				// 当年入职
				if (nowYear - officeYear == 0) {
					// 放假天数
					Holidays = WorkDayMath.mathYearDays(officeDate, years) * 5;
				}
				// 入职满一年
				else if (nowYear - officeYear > 0) {
					// 放假天数
					Holidays = 5 + (nowYear - officeYear);
				}
				float holidaysStart;
				// 判断员工是否有上年有剩余年假
				int count1 = kaoqinService.HasLastHolidays(person.getPersonId(), Integer.parseInt(years) - 1);
				if (count1 == 0) {
					holidaysStart = 0.000f;
					HolidaysEnd = holidaysStart + Holidays;
				} else {
					// 获取上年假期剩余,默认还剩0天
					holidaysStart = kaoqinService.getLastHolidays(person.getPersonId(), Integer.parseInt(years) - 1);
					HolidaysEnd = holidaysStart + Holidays;
				}
				KaoQinMessage msg = new KaoQinMessage();
				msg.setKjYear(Integer.parseInt(years));
				msg.setCompanyId(person.getCompanyId());
				msg.setCompanyName(person.getCompanyName());
				msg.setPersonName(person.getPersonName());
				msg.setPersonId(person.getPersonId());
				msg.setHolidays(Holidays);
				msg.setHolidaysStart(holidaysStart);
				msg.setOverTimeDaysStart(0);
				msg.setWorkDays01(workDayMonth[0]);
				msg.setOffDays01(0);
				msg.setSalaryDays01(0);
				msg.setWorkDays02(workDayMonth[1]);
				msg.setOffDays02(0);
				msg.setSalaryDays02(0);
				msg.setWorkDays03(workDayMonth[2]);
				msg.setOffDays03(0);
				msg.setSalaryDays03(0);
				msg.setWorkDays04(workDayMonth[3]);
				msg.setOffDays04(0);
				msg.setSalaryDays04(0);
				msg.setWorkDays05(workDayMonth[4]);
				msg.setOffDays05(0);
				msg.setSalaryDays05(0);
				msg.setWorkDays06(workDayMonth[5]);
				msg.setOffDays06(0);
				msg.setSalaryDays06(0);
				msg.setWorkDays07(workDayMonth[6]);
				msg.setOffDays07(0);
				msg.setSalaryDays07(0);
				msg.setWorkDays08(workDayMonth[7]);
				msg.setOffDays08(0);
				msg.setSalaryDays08(0);
				msg.setWorkDays09(workDayMonth[8]);
				msg.setOffDays09(0);
				msg.setSalaryDays09(0);
				msg.setWorkDays10(workDayMonth[9]);
				msg.setOffDays10(0);
				msg.setSalaryDays10(0);
				msg.setWorkDays11(workDayMonth[10]);
				msg.setOffDays11(0);
				msg.setSalaryDays11(0);
				msg.setWorkDays12(workDayMonth[11]);
				msg.setOffDays12(0);
				msg.setSalaryDays12(0);
				msg.setWorkDaysTotal(workDaysTotal);
				msg.setOffDaysTotal(0);
				msg.setSalaryDaysTotal(workDaysTotal);
				msg.setHolidaysTotal(0);
				msg.setHolidaysEnd(HolidaysEnd);
				msg.setOverTimeDaysTotal(0);
				msg.setLawDaysTotal(0);
				msg.setSickDaysTotal(0);
				msg.setPersonDaysTotal(0);
				msg.setKpi01(0);
				msg.setKpi02(0);
				msg.setKpi03(0);
				msg.setKpi04(0);
				msg.setKpi05(0);
				msg.setKpi06(0);
				msg.setKpi07(0);
				msg.setKpi08(0);
				msg.setKpi09(0);
				msg.setKpi10(0);
				msg.setKpi11(0);
				msg.setKpi12(0);
				msg.setRemark1(null);
				msg.setRemark2(null);
				msg.setRemark3(null);
				kaoqinMapper.insertPersonInit(msg);
			}
		}

		return map;
	}

	@ResponseBody
	@RequestMapping("/editActive")
	public Map<String, Object> locationUpdateStatus(Gy_Person employee) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			writeService.updateByActive(employee);
			map.put("status", 200);
			dataMap.put("msg", "");
			map.put("msg", "success");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("status", 400);
			map.put("msg", "error");
			dataMap.put("msg", e.getMessage());
		}
		dataMap.put("id", employee.getId());
		map.put("data", dataMap);
		return map;
	}

	@ResponseBody
	@RequestMapping("edit")
	public Map<String, Object> EmployeeUpdate(Gy_Person employee) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		System.out.println(employee);
		int result = writeService.updateByPrimaryKey(employee);

		if (result == 1) {
			map.put("status", 200);
			dataMap.put("msg", "修改成功");
			map.put("msg", "success");
		} else {
			map.put("status", 400);
			map.put("msg", "修改失败");
		}
		dataMap.put("id", employee.getId());
		map.put("data", dataMap);

		// 在员工部门调动表插入一条记录
		int personid = employee.getId().intValue();
		int deptid = employee.getDeptid();
		Date nowdate = new Date();
		GyPersonPredept predept = new GyPersonPredept(personid, deptid, nowdate);
		predeptService.insertPredept(predept);

		return map;
	}

	// 部门树
	@ResponseBody
	@RequestMapping("selectTreeNode_department.do")
	public Map<String, Object> selectTreeNode_department(Department department) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>(); // selectParentDeptName
		List<Map<String, Object>> departlist = readService.selectCompanyNameWithId(department);
		System.out.println(departlist);
		map.put("status", 200);
		map.put("msg", "success");
		// dataMap.put("page", 1);
		dataMap.put("records", departlist.size());
		dataMap.put("items", departlist);
		map.put("data", dataMap);
		return map;
	}

	// 导出excel表格
	@RequestMapping("exportExcel")
	public String exportExcel(String isActive, HttpServletResponse response) throws FileNotFoundException {
		return readService.exportExcel(isActive, response);
	}

	// 导入excel，初始化员工信息
	@ResponseBody
	@RequestMapping(value = "/readExcel")
	public Object readExcel(@RequestParam(value = "excelFile") MultipartFile file, HttpServletRequest request,
			HttpSession session) throws IOException {
		// 判断文件是否为空
		if (file == null)
			return ServerResponse.createByError("文件不能为空！");
		String name = file.getOriginalFilename();
		long size = file.getSize();
		if (name == null || ExcelUtil.EMPTY.equals(name) && size == 0)
			return ServerResponse.createByError("文件不能为空！");

		// 读取Excel数据到List中
		List<ArrayList<String>> list = new ExcelRead().readExcel(file);
		// list中存的就是excel中的数据，可以根据excel中每一列的值转换成你所需要的值（从0开始），如：
		for (int i = 0; i < list.size(); i++) {
			Object info = buildPersonByRowData(list.get(i), i + 1);

			if (info instanceof String)
				return ServerResponse.createByError((String) info);
			else {
				int id = employeeMapper.insert((GyPerson) info);
				if (id <= 0)
					return ServerResponse.createByError("插入数据库失败！");
			}
		}

		return ServerResponse.createBySuccess("上传成功！");
	}

	private Object buildPersonByRowData(List<String> rowData, int index) {
		if (rowData.size() < 40)
			return "excel文件列数不匹配！";
		GyPerson person = new GyPerson();
		String companyName = rowData.get(0);
		String departmentName = rowData.get(1);
		String personCode = rowData.get(2);
		String personName = rowData.get(3);
		String personEName = rowData.get(4);
		String sex = rowData.get(5);
		String nation = rowData.get(6);
		String isMarried = rowData.get(7);
		String postName = rowData.get(8);
		String identityNo = rowData.get(9);
		String homeAddr = rowData.get(10);

		String nowAddr = rowData.get(11);
		String birthDate = rowData.get(12);
		String graduateDate = rowData.get(13);
		String officeDate = rowData.get(14);
		String memberDate = rowData.get(15);
		String isMembered = rowData.get(16);
		String contractDate = rowData.get(17);
		String isContract = rowData.get(18);
		String leaveDate = rowData.get(19);
		String educationDegree = rowData.get(20);
		String school = rowData.get(21);
		String major = rowData.get(22);
		person.setMajor(major);
		String englishDegree = rowData.get(23);
		// 这里5行，数据库中只有3行
		String _HKMCPassport = rowData.get(29);
		String _ICEPerson = rowData.get(30);

		String _ICETel = rowData.get(31);
		String email = rowData.get(32);
		String mobile = rowData.get(33);
		String weiXin = rowData.get(34);
		String qq = rowData.get(35);

		String remark = rowData.get(36);
		String createTime = rowData.get(37);
		String updateTime = rowData.get(38);
		String isActive = rowData.get(39);

		long companyId = companyMapper.selectCompanyIDByName(companyName);
		if (companyId <= 0) {
			return "第" + index + "行的公司名称有误！";
		} else
			person.setCompanyid(companyId);

		Department department = departmentMapper.selectByDeptname(departmentName);
		if (department == null) {
			return "第" + index + "行的部门名称信息有误！";
		} else
			person.setDeptid(department.getId());

		int personCount = personMapper.selectPersonCodeHasExist(personCode);
		if (personCount != 0) {
			return "第" + index + "行员工的代号（personCode）重复了";
		} else
			person.setPersoncode(personCode);

		person.setPersonname(personName);
		person.setPersonename(personEName);

		int sexId = configDetailMapper.selectIdByName(sex);
		if (sexId > 0)
			person.setSexid(sexId);

		Integer nationId = configDetailMapper.selectIdByName(nation);
		if (nationId != null)
			person.setNationid(nationId);

		Integer isMarriedId = configDetailMapper.selectIdByName(isMarried);
		if (isMarriedId != null)
			person.setMarriageid(isMarriedId);

		Integer postId = configDetailMapper.selectIdByName(postName);
		if (postId != null)
			person.setPostid(postId);

		person.setIdentityno(identityNo);
		person.setHomeaddr(homeAddr);
		person.setNowaddr(nowAddr);

		Date birthDate2 = parseStringToDate(birthDate);
		if (birthDate2 != null)
			person.setBirthdate(birthDate2);

		Date graduateDate2 = parseStringToDate(graduateDate);
		if (graduateDate2 != null)
			person.setGraduatedate(graduateDate2);

		Date officeDate2 = parseStringToDate(officeDate);
		if (officeDate2 != null)
			person.setOfficedate(officeDate2);

		Date memberDate2 = parseStringToDate(memberDate);
		if (memberDate2 != null)
			person.setMemberdate(memberDate2);

		Date createTime2 = parseStringToDate(createTime);
		if (createTime2 != null)
			person.setCreatetime(createTime2);

		Date updateTime2 = parseStringToDate(updateTime);
		if (updateTime2 != null)
			person.setUpdatetime(updateTime2);

		try {
			Byte isMember = Byte.parseByte(isMembered);
			person.setIsmembered(isMember);
		} catch (NumberFormatException e) {
		}

		Date contractDate2 = parseStringToDate(contractDate);
		if (contractDate2 != null)
			person.setContractdate(contractDate2);

		Date leaveDate2 = parseStringToDate(leaveDate);
		if (leaveDate2 != null)
			person.setLeavedate(leaveDate2);

		try {
			Byte isContract2 = Byte.parseByte(isContract);
			person.setIsmembered(isContract2);
		} catch (NumberFormatException e) {
		}

		try {
			int educationDegree2 = Integer.parseInt(educationDegree);
			person.setEducationdegree(educationDegree2);
		} catch (NumberFormatException e) {
		}

		try {
			int englishDegree2 = Integer.parseInt(englishDegree);
			person.setEnglishdegreeid(englishDegree2);
		} catch (NumberFormatException e) {
		}

		person.setSchool(school);
		person.setMobile(mobile);
		person.setWeixin(weiXin);
		person.setQq(qq);
		person.setHkmcpassport(_HKMCPassport);
		person.setIceperson(_ICEPerson);
		person.setIcetel(_ICETel);
		person.setEmail(email);
		person.setRemark(remark);

		if (isActive.equals("在职"))
			person.setActive((byte) 1);
		else
			person.setActive((byte) 0);
		return person;
	}

	private Date parseStringToDate(String dateString) {
		SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy/MM/dd");
		SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy年MM月dd日");
		Date date = null;
		try {
			date = simpleDateFormat1.parse(dateString);
		} catch (ParseException px1) {
			try {
				date = simpleDateFormat2.parse(dateString);
			} catch (ParseException px2) {
				try {
					date = simpleDateFormat3.parse(dateString);
				} catch (ParseException px3) {
					return null;
				}
			}
		}
		return date;
	}
}
